<template>
  <div class="account-box">
    <div class="toggle">
      <a href="javascript:;" v-if="isMsgLogin"  @click="isMsgLogin = false">
        <i class="iconfont icon-user"></i>使用账号登录
      </a>
      <a href="javascript:;" v-else  @click="isMsgLogin=true">
        <i class="iconfont icon-msg"></i>使用短信登录
      </a>
    </div>
    <!-- errors 是指插件抛出的错误提示 -->
    <Form class="form" ref="formCom" :validation-schema="schema" v-slot="{errors}" autocomplete="off">
      <template v-if="!isMsgLogin" >
       <div class="form-item">
        <div class="input">
          <i class="iconfont icon-user"></i>
          <Field v-model="form.account" type="text" placeholder="请输入用户名或手机号" :class="{error: errors.account}" name="account" />
        </div>
        <div class="error" v-if="errors.account">
          <i class="iconfont icon-warning">{{ errors.account }}</i>
        </div>
       </div>
       <div class="form-item">
        <div class="input">
          <i class="iconfont icon-lock"></i>
          <Field v-model="form.password" type="password" placeholder="请输入用户密码" :class="{error: errors.password}" name="password" />
        </div>
        <div class="error" v-if="errors.password">
          <i class="iconfont icon-warning">{{ errors.password }}</i>
        </div>
       </div>
      </template>
      <template v-else>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <Field v-model="form.mobile" type="text" placeholder="请输入手机号" :class="{error: errors.mobile}" name="mobile" />
          </div>
          <div class="error" v-if="errors.mobile">
            <i class="iconfont icon-warning">{{ errors.mobile }}</i>
          </div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-code"></i>
            <Field v-model="form.code" type="password" placeholder="请输入验证码" :class="{error: errors.code}" name="code" />
            <span class="code" @click="send">{{time > 0? `${ time }秒后重发` : '发送验证码'}}</span>
          </div>
          <div class="error" v-if="errors.code">
            <i class="iconfont icon-warning">{{ errors.code }}</i>
          </div>
        </div>
      </template>
      <div class="form-item">
        <div class="agree">
          <Field as="XtxCheckbox"  v-model="form.isAgree" name="isAgree" />
          <span>我已同意</span>
          <a href="javascript:;">《隐私条款》</a>
          <span>和</span>
          <a href="javascript:;">《服务条款》</a>
        </div>
        <div class="error" v-if="errors.isAgree">
          <i class="iconfont icon-warning">{{ errors.isAgree }}</i>
        </div>
      </div>
      <a href="javascript:;" class="btn" @click="login">登录</a>
    </Form>
    <div class="action">
      <a href="https://graph.qq.com/oauth2.0/authorize?client_id=100556005&response_type=token&scope=all&redirect_uri=http%3A%2F%2Fwww.corho.com%3A8080%2F%23%2Flogin%2Fcallback">
        <img src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png" alt="">
      </a>
      <div class="url">
        <a href="javascript:;">忘记密码</a>
        <a href="javascript:;">免费注册</a>
      </div>
    </div>
  </div>
</template>

<script>
import { reactive, ref, watch, onMounted } from 'vue'
import { Form, Field } from 'vee-validate'
import { userMobileLogin, userAccountLogin, userMobileLoginMsg } from '@/api/user'
import { useIntervalFn } from '@vueuse/core'
import { useStore } from 'vuex'
import schema from '@/utils/vee-validate-schema'
import Message from '@/components/library/Message.js'
import { useRoute, useRouter } from 'vue-router'
export default {
  name: 'LoginForm',
  components: {
    Form,
    Field
  },
  setup () {
    // 切换短信登录
    const isMsgLogin = ref(false)
    // 定义表单数据
    const form = reactive({
      isAgree: true,
      account: null,
      password: null,
      mobile: null,
      code: null
    })

    // 校验规则对象
    const mySchema = {
      account: schema.account,
      password: schema.password,
      mobile: schema.mobile,
      code: schema.code,
      isAgree: schema.isAgree
    }
    console.log(mySchema)
    const formCom = ref(null)
    // 监听isMsgLogin是否有重置表单 切换登录方式时重置表单
    watch(isMsgLogin, () => {
      // 重置数据
      form.isAgree = true
      form.account = null
      form.password = null
      form.mobile = null
      form.code = null
      // 由于切换的过程中组件是不会被销毁的，所以数据依旧会渲染在表单，类似与show，Form提供了一种重置表单数据的方法 resetForm
      formCom.value.resetForm()
    })

    const store = useStore()
    const router = useRouter()
    const route = useRoute()
    const login = async () => {
      // vee-validate Form组件提供了一个可以获取所有表单校验结果的方法 validate 但是返回的promise
      const value = await formCom.value.validate()
      if (value) {
        try {
          let data = null
          // 判断登录方式
          // 1.准备一个API做为手机登录
          // 2.调用API函数
          // 3.成功： 存储用户信息 + 跳转至来源页或者首页 + 消息提示
          // 4.失败：消息提示
          if (isMsgLogin.value) {
            // 手机验证码登录
            const { mobile, code } = form
            data = await userMobileLogin(mobile, code)
            console.log(data)
          } else {
            // 账号登录
            const { account, password } = form
            data = await userAccountLogin(account, password)
          }
          const { id, account, avatar, mobile, nickname, token } = data.result
          // 使用本地存储存储登录返回的数据
          store.commit('user/setUser', { id, account, avatar, mobile, nickname, token })
          // 合并购物车商品
          store.dispatch('cart/mergeLocalCart').then(() => {
            router.push(route.query.redirectUrl || '/')
            Message({ text: '登录成功', type: 'success' })
          })
        } catch (err) {
          console.log(err)
        }
      }
    }

    // 设置验证码倒计时
    const time = ref(0)
    // 使用vue提供的方法 useInterValFn 参数1：回调函数， 参数2：执行间隔 参数3：是否立即执行
    const { pause, resume } = useIntervalFn(() => {
      time.value--
      if (time.value <= 0) {
        pause()
      }
    }, 1000)
    onMounted(() => {
      pause()
    })

    // 点击发送验证码
    const send = () => {
      const valid = mySchema.mobile(form.mobile)
      // 判断表单是否校验成功，成功的话发送验证码请求
      if (valid === true) {
        console.log(valid)
        if (time.value === 0) {
          userMobileLoginMsg(form.mobile)
          time.value = 60
          resume()
        }
      } else {
        // 如果表单手机号没有输入的情况下点击发送验证码，则重新提醒vee-validate 表单mobile验证提示错误
        formCom.value.setFieldError('mobile', valid)
      }
    }
    return { isMsgLogin, form, schema: mySchema, formCom, login, time, send }
  }
}
</script>

<style lang="less" scoped>
.account-box {
  .toggle {
    padding: 15px 40px;
    text-align: right;
    a {
      color: @xtxColor;
      i {
        font-size: 14px;
      }
    }
  }
  .form {
    padding: 0 40px;
    &-item{
      margin-bottom: 28px;
      .input {
        position: relative;
        height: 36px;
        >i {
          width: 34px;
          height: 34px;
          background: #cfcfcf;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }
        input {
          padding-left: 44px;
          border: 1px solid #cfcfcf;
          height: 36px;
          line-height: 36px;
          width: 100%;
          &.error {
            border-color: @priceColor;
          }
          &.active,&:focus {
            border-color: @xtxColor;
          }
        }
        .code {
          position:absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 14px;
          background: #f5f5f5;
          color: #666;
          width: 90px;
          height: 34px;
          cursor: pointer;
        }
      }
      >.error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: @priceColor;
        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }
    .agree {
      a {
        color: #069;
      }
    }
    .btn {
      display: block;
      width: 100%;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: @xtxColor;
      &.disabled {
        background: #cfcdcd;
      }
    }

  }
  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}
</style>
